package com.zjhcsoft.shop.sys.shoputil;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.zjhcsoft.shop.service.UserService;
import com.zjhcsoft.shop.sys.constant.Constants;
import com.zjhcsoft.shop.model.User;
import com.zjhcsoft.util.Base64;
import com.zjhcsoft.util.CommonUtil;
import com.zjhcsoft.util.Md5Util;
import com.zjhcsoft.util.SpringContextHelper;

/**
 * 用户相关操作辅助类
 */

public class UserUtil {

	/**
	 * 根据Cookie信息获取当前登录用户信息，如果不合法则返回null
	 * 
	 * @param cookies
	 * @return
	 */
	public static User getUserFromCookies() {
		final Log logger = LogFactory.getLog(UserUtil.class);
		HttpServletRequest request = ServletActionContext.getRequest();
		Cookie[] cookies = request.getCookies();
		// 以下操作判断用户是否有用户登录的cookie信息
		String cookievalue = "";
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(Constants.USER_KEY)) {
					cookievalue = cookie.getValue();
					break;
				}
				;
			}
		}
		// 判断时候存在用户cookie信息，没有则跳转到登录页面
		if (!"".equals(cookievalue)) {
			// 先得到的CookieValue进行Base64解码
			try {
				String cookieValueAfterDecode = new String(Base64.decode(cookievalue), "UTF-8");
				// 对解码后的值进行分拆,得到一个数组,如果数组长度不为3,就是非法登陆
				String cookieValues[] = cookieValueAfterDecode.split(Constants.WORD_SEPARATOR);
				if (cookieValues.length == 2) {
					String loginName = cookieValues[0];
					String token = cookieValues[1];
					UserService userService = (UserService) SpringContextHelper.getBean("userServiceImpl");
					// 验证登录信息
					User user = userService.loadByLoginName(loginName);
					String server_token = Md5Util.getMd5(user.getLoginName()
							+ user.getPassword());
					// 验证token
					if (server_token.equals(token)) {
						return user;
					}
				}
			} catch (UnsupportedEncodingException e1) {
				logger.error(e1.getMessage());
			}
		}
		return null;
	}
	
	/**
	 * 判断是否是当前登录用户
	 * @param loginName
	 * @return
	 */
	public static boolean isCurrentUser(String loginName) {
		User currentUser = getUserFromCookies();
		if (currentUser != null && (currentUser.getLoginName().equals(loginName) 
				|| CommonUtil.isEmpty(loginName))) {
			return true;
		} else {
			return false;
		}
	}
	/**
	 * 根据用户名获取用户
	 * @param loginName
	 * @return
	 */
	public static User getUser(String loginName) {
		UserService userService = (UserService) SpringContextHelper.getBean("userService");
		User user = userService.loadByLoginName(loginName);
		return user;
	}

}